package com.itany.service.impl;

import com.itany.entity.*;
import com.itany.mapper.AnnexMapper;
import com.itany.mapper.NoticeMapper;
import com.itany.mapper.ServerCompanyMapper;
import com.itany.mapper.UserMapper;
import com.itany.service.ServerCompanyService;
import com.itany.utils.OssClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ServerCompanyServiceImpl implements ServerCompanyService {
    @Autowired
    private ServerCompanyMapper mapper;
    @Autowired
    private AnnexMapper annexMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Map<String, Object>> queryByParams(String name, String phone, Integer memberId, Integer flag, Integer type) {
        List<ServerCompany> list = mapper.selectByParams(name,phone,memberId,flag,type);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if(!list.isEmpty()) {
            for (ServerCompany serverCompany : list) {
                Map<String, Object> u = new HashMap<>();
                u.put("id",serverCompany.getId());
                u.put("name",serverCompany.getName());
                u.put("phone",serverCompany.getPhone());
                u.put("linkman",serverCompany.getLinkman());
                u.put("address",serverCompany.getAddress());
                u.put("gps",serverCompany.getGps());
                u.put("childCount",serverCompany.getChildCount());
                u.put("joindate",serverCompany.getJoindate());
                u.put("flag",serverCompany.getFlag());
                u.put("level",serverCompany.getLevel());
                mapList.add(u);
            }
            return mapList;
        }else{
            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void modifyStatus(Integer id,Integer managerUserId) {
        ServerCompany serverCompany = mapper.selectByPrimaryKey(id);
        if(serverCompany.getFlag() == 1){
            serverCompany.setFlag(0);
            UserExample userExample = new UserExample();
            userExample.or().andCompanyidEqualTo(id);
            List<User> users = userMapper.selectByExample(userExample);
            if(!users.isEmpty()){
                for(User user:users){
                    Notice notice = new Notice();
                    notice.setTitle("管理员操作");
                    notice.setInfo("加盟的服务商被禁用!");
                    notice.setManageruserid(managerUserId);
                    notice.setUserid(user.getId());
                    notice.setFlag(1);
                    notice.setCreatedate(new Date());
                    noticeMapper.insertSelective(notice);
                }
            }
        }else{
            serverCompany.setFlag(1);
        }
        mapper.updateByPrimaryKeySelective(serverCompany);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Map<String, Object>> queryCompanies() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<ServerCompany> serverCompanies = mapper.selectByExample(new ServerCompanyExample());
        Map<String,Object> map = new HashMap<>();
        map.put("id",-1);
        map.put("text","请选择服务商");
        list.add(map);
        map = new HashMap<>();
        map.put("id",0);
        map.put("text","平台人员");
        list.add(map);
        if (!serverCompanies.isEmpty()){
            for(ServerCompany serverCompany:serverCompanies){
                Map<String,Object> u = new HashMap<>();
                u.put("id",serverCompany.getId());
                u.put("text",serverCompany.getName());
                list.add(u);
            }
        }
        return list;
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Map<String, Object> findById(Integer id) {
        ServerCompany serverCompany = mapper.selectById(id);
        if(serverCompany != null){
            Map<String,Object> map = new HashMap<>();
            map.put("name",serverCompany.getName());
            map.put("address",serverCompany.getAddress());
            map.put("phone",serverCompany.getPhone());
            map.put("linkman",serverCompany.getLinkman());
            map.put("scale",serverCompany.getScale());
            map.put("childCount",serverCompany.getChildCount());
            map.put("type",serverCompany.getType());
            map.put("createdate",serverCompany.getCreatedate());
            map.put("gps",serverCompany.getGps());
            map.put("info",serverCompany.getInfo());
            List<String> imageUrls = new ArrayList<>();
            AnnexExample annexExample1 = new AnnexExample();
            annexExample1.or().andKeyidEqualTo(id).andTypeEqualTo("2").andTabletypeEqualTo(2);
            List<Annex> annexList1 = annexMapper.selectByExample(annexExample1);
            if(!annexList1.isEmpty()){
                for(Annex annex : annexList1){
                    imageUrls.add(annex.getPath()+annex.getFilename());
                }
            }
            AnnexExample annexExample2 = new AnnexExample();
            annexExample2.or().andKeyidEqualTo(id).andTypeEqualTo("3").andTabletypeEqualTo(2);
            List<Annex> annexList2 = annexMapper.selectByExample(annexExample2);
            if(!annexList2.isEmpty()){
                Annex annex = annexList2.get(0);
                imageUrls.add(annex.getPath()+annex.getFilename());
            }
            map.put("imageUrls",imageUrls);
            return map;
        }else{
            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public void modifyInfo(Integer id, String name, String address, String phone, String linkman, String scale, Integer type, String createdate, String gps, String info, MultipartFile[] imgs, String existingImages) {
        ServerCompany serverCompany = new ServerCompany();
        serverCompany.setId(id);
        serverCompany.setName(name);
        serverCompany.setAddress(address);
        serverCompany.setPhone(phone);
        serverCompany.setLinkman(linkman);
        serverCompany.setScale(scale);
        serverCompany.setType(type);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            serverCompany.setCreatedate(dateFormat.parse(createdate));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        serverCompany.setGps(gps);
        serverCompany.setInfo(info);
               AnnexExample annexExample = new AnnexExample();
               annexExample.or().andTypeEqualTo("2").andKeyidEqualTo(id).andTabletypeEqualTo(2);
               List<Annex> annexList = annexMapper.selectByExample(annexExample);
               annexMapper.deleteByExample(annexExample);
               String[] exists = existingImages.split(",");
               for (String exist : exists){
                   try {
                       if(exist != null && !exist.isEmpty()){
                           MultipartFile file = OssClientUtil.convert(exist);
                           Map<String,Object> map = OssClientUtil.uploadImage("serviceCompany/",file);
                           String path = map.get("path").toString() + "/serviceCompany/";
                           String filename = map.get("filename").toString();
                           Annex annex = new Annex();
                           annex.setPath(path);
                           annex.setFilename(filename);
                           annex.setType("2");
                           annex.setKeyid(id);
                           annex.setTabletype(2);
                           annexMapper.insertSelective(annex);
                       }
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }
               }
                if(!annexList.isEmpty()) {
                    for(Annex annex : annexList){
                        String key = "serviceCompany/" + annex.getFilename();
                        OssClientUtil.deleteImage(key);
                    }
                }
        if (imgs != null) {
               for(MultipartFile file : imgs){
                   try {
                       Map<String,Object> map = OssClientUtil.uploadImage("serviceCompany/",file);
                       String path = map.get("path").toString() + "/serviceCompany/";
                       String filename = map.get("filename").toString();
                       Annex annex = new Annex();
                       annex.setPath(path);
                       annex.setFilename(filename);
                       annex.setType("2");
                       annex.setKeyid(id);
                       annex.setTabletype(2);
                       annexMapper.insertSelective(annex);
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }
               }
        }
        mapper.updateByPrimaryKeySelective(serverCompany);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Map<String, Object> findCompany(Integer id) {
        ServerCompany serverCompany = mapper.selectById(id);
        if(serverCompany != null){
            Map<String,Object> map = new HashMap<>();
            map.put("name",serverCompany.getName());
            map.put("address",serverCompany.getAddress());
            map.put("phone",serverCompany.getPhone());
            map.put("linkman",serverCompany.getLinkman());
            map.put("scale",serverCompany.getScale());
            map.put("childCount",serverCompany.getChildCount());
            map.put("type",serverCompany.getType());
            map.put("createdate",serverCompany.getCreatedate());
            map.put("gps",serverCompany.getGps());
            map.put("info",serverCompany.getInfo());
            List<String> imageUrls = new ArrayList<>();
            AnnexExample annexExample1 = new AnnexExample();
            annexExample1.or().andKeyidEqualTo(id).andTypeEqualTo("2").andTabletypeEqualTo(2);
            List<Annex> annexList1 = annexMapper.selectByExample(annexExample1);
            if(!annexList1.isEmpty()){
                for(Annex annex : annexList1){
                    imageUrls.add(annex.getPath()+annex.getFilename());
                }
            }
            map.put("imageUrls",imageUrls);
            return map;
        }else{
            return null;
        }
    }
}
